const ActionTypes = {
  INIT: '@@redux/INIT'
}

export const createStore = ( reducer, preloadedState, enhancer ) => {
    if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
        enhancer = preloadedState;
        preloadedState = undefined;
    }

    if( typeof enhancer === 'function' ) {
        return enhancer(createStore)(reducer, preloadedState);
    }

    if(typeof reducer !== 'function') {
        throw new Error('传入的reducer必须为一个函数');
    }

    let state = preloadedState;
    let fnArr = [];
    let isDispatching = false;
    const getState = () => {
        return state;
    }

    const dispatch = action => {
        if ( action.toString() !== '[object Object]' ) {
            throw new Error('action必须为简单对象');
        }
        if ( typeof action.type === 'undefined' ) {
            throw new Error('type is undefined');
        }
        if(isDispatching) {
           throw new Error('不能在reducer中调用dispatch');
        }

        isDispatching = true;
        state = reducer(state, action);
        isDispatching = false;
        fnArr.forEach( item => item() );
    }

    const subscribe = fn => {
        fnArr.push(fn);
        return () => {
            const index = fnArr.indexOf(fn);
            fnArr.splice(index, 1);
        }
    }
    dispatch({type:ActionTypes.INIT});
    return {
        getState,
        dispatch,
        subscribe
    }
}
export const combineReducers = (reducers) => {
    const tempReducers = {};
    for (let key in reducers) {
        let reducer = reducers[key];

        if(typeof reducer === 'undefined') {
            console.error(`reducer ${key} 的值是undefined`)
        }
        if (typeof reducer === 'function') {
            tempReducers[key] = reducer;

        }
    }
    for (let key in tempReducers) {
         const reducer = tempReducers[key];
         const state = reducer(undefined, {type: ActionTypes.INIT});

         if(typeof state === 'undefined') {
           throw new Error(`Reducer ${key} 的返回值为undefined，该reducer非法`);
         }
    }

    return (state={}, action) => {
        for (let key in tempReducers) {
           const newState = tempReducers[key](state[key], action);
           state[key] = newState;
        }
        return state;
    }

}

export const bindActionCreators = (actionCreators, dispatch) => {
    const actionObj = {};
    console.log(actionCreators)
    if (typeof actionCreators !== 'object' || actionCreators == null) {
        throw new Error('actions必须是一个对象且不能为null');
    }
    for  (let key in actionCreators) {
        const creator = actionCreators[key];

        if (typeof creator === 'function') {
            actionObj[key] = (...arg) => dispatch(creator(...arg));
        }
    }
    return actionObj
}
